package com.easyselection.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.easyselection.dto.Result;
import com.easyselection.entity.ShopType;
import com.easyselection.mapper.ShopTypeMapper;
import com.easyselection.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyselection.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //1.在redis当中查询商铺类型列表缓存是否存在
        String key = RedisConstants.CACHE_SHOP_TYPE_KEY;
        List<String> shopTypeListJson = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2.存在直接返回
        if(CollectionUtil.isNotEmpty(shopTypeListJson)){
            //将所有的jsonList转化为对象list,并排序
            List<ShopType> shopTypeList = shopTypeListJson.stream()
                    .map(str->JSONUtil.toBean(str, ShopType.class))
                    .sorted(Comparator.comparingInt(ShopType::getSort))
                    .collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }
        //3. 不存在,查询数据库使用mp提供的接口
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();

        //4.数据库中不存在, 返回错误
        if (CollectionUtil.isEmpty(shopTypeList)){
            return Result.fail("商铺类型列表为空!");
        }
        shopTypeListJson = shopTypeList.stream().sorted(Comparator.comparingInt(ShopType::getSort))
                .map(shopType -> JSONUtil.toJsonStr(shopType))
                .collect(Collectors.toList());

        //5.保存到Redis当中
        stringRedisTemplate.opsForList().rightPushAll(key, shopTypeListJson);
        //6.返回信息
        return Result.ok(shopTypeList);
    }
}
